package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @Author: Bin
 * @description:
 * @date: 2025-07-14 10:01
 */

@Component
public class CacheClient {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }


    // 缓存穿透get
    public <R, ID> R getWithPassThrough(String keyPrefix,
                                        ID id, Class<R> type,
                                        Function<ID, R> dbFallback,
                                        Long time, TimeUnit unit) {
        // redis中的键
        String key = keyPrefix + id;

        String value = stringRedisTemplate.opsForValue().get(key);
        // 不为空
        if (StrUtil.isNotBlank(value)) {
            return JSONUtil.toBean(value, type);
        }
        // string值为""
        if (value != null) {
            return null;
        }
        // redis中没有 解决缓存穿透 并重建缓存
        R r = dbFallback.apply(id);
        if (r == null) {
            stringRedisTemplate.opsForValue().set(key, "", time, unit);
            return null;
        }
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(r), time, unit);
        return r;
    }

    //缓存击穿get
    public <R, ID> R getWithLogicalExpire(String keyPrefix,
                                          ID id, Class<R> innerType,
                                          Function<ID, R> dbFallback,
                                          Long time, TimeUnit unit) {
        String key = keyPrefix + id;

        String json = stringRedisTemplate.opsForValue().get(key);
        if (json == null) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), innerType);
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
            // 没过期
            return r;
        }
        // 过期了 需要重建缓存 新建一个线程进行缓存重建
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isGetLock = tryLock(lockKey);
        if (isGetLock) {
            // 获取锁成功 先判断是不是其他线程刚重建好缓存释放的锁
            json = stringRedisTemplate.opsForValue().get(key);
            // 查到了 判断是否过期
            redisData = JSONUtil.toBean(json, RedisData.class);
            r = JSONUtil.toBean((JSONObject) redisData.getData(), innerType);
            if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
                // 未过期 直接返回
                return r;
            }
            // 缓存过期了 新建一个线程进行缓存重建(使用线程池的方式)
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    saveShop2Redis(id, time, unit, dbFallback);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    // 重建后需要释放锁
                    unLock(lockKey);
                }
            });
        }
        // 无论是重建完成 还是获取锁失败 都会返回信息
        return r;
    }

    private boolean tryLock(String key) {
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(lock);
    }

    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    private <ID, R> void saveShop2Redis(ID id, Long expireSeconds, TimeUnit unit, Function<ID, R> dbFallback) throws InterruptedException {
        R r = dbFallback.apply(id);
        setWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY + id, r, expireSeconds, unit);

    }

}
